const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
const router = new Router()
const bodyParser = require('koa-bodyparser')

const routes = require('./routes')
const config = require('./config/default')

routes(router)

app
  .use(bodyParser())
  .use(async (ctx, next) => {
    const res = ctx.response
    res.set("Access-Control-Allow-Origin", "http://localhost:3000")
    res.set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
    res.set("Access-Control-Allow-Credentials", true)
    res.set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
    // 以下两项打印出来的疑问
    // console.log('res', res)
    // console.log('body', ctx.body)
    return next()
  })
  .use(async (ctx, next) => {
    try {
      await next()
      ctx.body = {
        success: true,
        data: ctx.body
      }
    } catch (err) {
      ctx.status = err.status || 500;
      ctx.body = {
        success: false,
        msg: `internel error: ${err.message}`
      }
      ctx.app.emit('error', err, ctx);
    }
  })
  .use(router.routes())
  .use(router.allowedMethods())

app.listen(config.port, (err) => {
  console.log(`port ${config.port} is listened..`)
})